package com.zhangxun.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeCloseRequest;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeCloseResponse;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.zhangxun.domain.Order;
import com.zhangxun.dto.PrePayDto;
import com.zhangxun.feign.PayOrderFeign;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@Api(tags = "支付宝支付相关接口管理")
public class ALiPayController {
    @Value("${aliPay.appId}")
    private String appId;
    @Value("${aliPay.privateKey}")
    private String privateKey;
    @Value("${aliPay.aliPublicKey}")
    private String aliPublicKey;
    @Autowired
    private PayOrderFeign payOrderFeign;

    /**
     * 创建预支付单  返回二维码给前端
     *
     * @return
     */
    @PostMapping("/p/order/pay")
    @ApiOperation(value = "创建预支付单")
    public ResponseEntity<String> prePay(@RequestBody PrePayDto prePayDto) throws AlipayApiException {
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipaydev.com/gateway.do",
                appId,
                privateKey,
                "json",
                "UTF-8",
                aliPublicKey,
                "RSA2");
        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
        //设置异步通知回调地址
        request.setNotifyUrl("http://4muy56.natappfree.cc/aliNotify");
        JSONObject bizContent = new JSONObject();
        //设置商户订单编号
        String orderNumber = prePayDto.getOrderNumber();
        bizContent.put("out_trade_no",orderNumber );
        Order order = payOrderFeign.loadById(orderNumber);
        //设置交易金额
        bizContent.put("total_amount", order.getActualTotal());
        //设置商品名称
        bizContent.put("subject", order.getProdName());
        request.setBizContent(bizContent.toString());
        AlipayTradePrecreateResponse response = alipayClient.execute(request);
        if (response.isSuccess()) {
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
        //获取响应中的二维码返回给前端
        String qrCode = response.getQrCode();
        return ResponseEntity.ok(qrCode);
    }

    /**
     * 异步通知：
     *   1.对于重复通知处理
     *   2.验签 （确认异步通知是否来自于支付宝）
     *   3,项目未上线需要内网穿透
     * @param map
     * @return
     */
    @PostMapping("/aliNotify")
    public String aliNotify(@RequestParam Map<String,String> map) throws AlipayApiException {
        //验证签名
        boolean  signVerified = AlipaySignature.rsaCheckV1(map,
                aliPublicKey,
                "UTF-8",
                "RSA2") ;
        //判断验签是否通过
        if(signVerified){
            //获取订单的支付状态
            String tradeStatus = map.get("trade_status");
            //判断订单的状态是否为支付成功
            if(tradeStatus.equals("TRADE_SUCCESS")){
                //支付成功  修改商户数据库中订单的状态为 待发货
                //获取商户订单号
                String orderNo = map.get("out_trade_no");
                //最好使用消息队列
                payOrderFeign.updateOrderStatus(orderNo);
            }
            return "success";
        }
        return "";
    }
    /**
     * 主动查询支付宝中订单状态
     */
    @PostMapping("/queryTradeStatus")
    @ApiOperation(value = "主动查询支付宝中订单状态")
    public Boolean queryTradeStatus(@RequestBody String orderNo) throws AlipayApiException {
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipaydev.com/gateway.do",
                appId,
                privateKey,
                "json",
                "UTF-8",
                aliPublicKey,
                "RSA2");
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        request.setBizContent("{" +
                "  \"out_trade_no\":\""+orderNo+"\"," +
                "}");
        AlipayTradeQueryResponse response = alipayClient.execute(request);
        if(response.isSuccess()){
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
        String tradeStatus = response.getTradeStatus();
        return "TRADE_SUCCESS".equals(tradeStatus);
    }
    @PostMapping("/closePrePayOrder")
    public void closePrePayOrder(@RequestBody String orderNo) throws AlipayApiException {
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipaydev.com/gateway.do",
                appId,
                privateKey,
                "json",
                "UTF-8",
                aliPublicKey,
                "RSA2");
        AlipayTradeCloseRequest request = new AlipayTradeCloseRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", orderNo);
        request.setBizContent(bizContent.toString());
        AlipayTradeCloseResponse response = alipayClient.execute(request);
        if(response.isSuccess()){
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
    }
}
